<template>
    <div class="box">
        <BCrudTable 
            :apiObj="$api.system" 
            v-model="columns"
            @showModalEvent="showModal" 
            ref="tableRef" 
            v-model:modalFormData="modalFormData"
            v-model:rulesRef="rulesRef"
            @submitEvent="submitEvent"
            >
            <template #bodyCell="{ text, record, index, column }">
                <span v-if="column.key === 'title'">
                    <!-- <component :is="record.meta.icon" /> -->
                    {{ record.meta.title }}
                </span>
                <span v-if="column.key === 'type'">
                    <template v-if="record.meta.menu_type === 'menu'">
                        菜单
                    </template>
                    <template v-if="record.meta.menu_type === 'button'">
                        按钮
                    </template>
                    <template v-if="record.meta.menu_type === 'link'">
                        外链
                    </template>
                    <template v-if="record.meta.menu_type === 'iframe'">
                        Iframe
                    </template>
                </span>
                <span v-if="column.key === 'hidden_breadcrumb'">
                    <a-switch
                        checked-children="是" 
                        un-checked-children="否"
                        :loading="isWatchLoading"
                        @change="onSwitchChange(record)" 
                        v-model:checked="record.meta.hidden_breadcrumb"
                        size="small" />
                </span>
                <span v-if="column.key === 'hidden'">
                    <a-switch
                        checked-children="是" 
                        un-checked-children="否"
                        @change="onSwitchChange(record)"
                        v-model:checked="record.meta.hidden"
                        size="small" />
                </span>
                <span v-if="column.key === 'affix'">
                    <a-switch
                        checked-children="是" 
                        un-checked-children="否"
                        @change="onSwitchChange(record)" 
                        v-model:checked="record.meta.affix"
                        size="small" />
                </span>
                <!-- <span v-if="column.key === 'fullpage'">
                    <a-switch
                        checked-children="是" 
                        un-checked-children="否"
                        @change="onSwitchChange({ id: record.id, fullpage: record.meta.fullpage })" 
                        v-model:checked="record.meta.fullpage"
                        size="small" />
                </span> -->
                <span v-if="column.key === 'icon'">
                    <BIconBox v-model:iconModel="record.meta.icon" @on-select-icon="onIconChange(record)" />
                </span>
            </template>
            <template #title>
                <a-form-item label="显示名称" name="title" v-bind="tableRef.validateInfos.title">
                    <a-input v-model:value="modalFormData.title" placeholder="请输入显示名称（title）" />
                </a-form-item>
            </template>
            <template #name>
                <a-form-item label="路由名称" name="name" v-bind="tableRef.validateInfos.name">
                    <a-input v-model:value="modalFormData.name" placeholder="请输入路由名称（name）" />
                </a-form-item>
            </template>
            <template #path>
                <a-form-item label="路由地址" name="path" v-bind="tableRef.validateInfos.path">
                    <a-input v-model:value="modalFormData.path" placeholder="请输入路由地址（path）" />
                </a-form-item>
            </template>
            <template #component>
                <a-form-item label="组件路径" name="component" v-bind="tableRef.validateInfos.component">
                    <a-input v-model:value="modalFormData.component" placeholder="请输入组件路径（component）" />
                </a-form-item>
            </template>
            <template #redirect>
                <a-form-item label="重定向" name="redirect" v-bind="tableRef.validateInfos.redirect">
                    <a-input v-model:value="modalFormData.redirect" placeholder="请输入重定向地址（redirect）" />
                </a-form-item>
            </template>
            <template #parent>
                <a-form-item label="父级菜单" name="parent" v-bind="tableRef.validateInfos.parent">
                    <a-tree-select
                        v-model:value="modalFormData.parent"
                        show-search
                        style="width: 100%"
                        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                        placeholder="为空则默认为顶级菜单"
                        searchPlaceholder="Search"
                        allow-clear
                        tree-default-expand-all
                        :tree-data="treeData"
                        tree-node-filter-prop="label"
                    >
                    </a-tree-select>
                </a-form-item>
            </template>
        </BCrudTable>
    </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, computed } from 'vue';
import { useMenusStore } from '@/stores/menus';
import BCrudTable from '@/components/BCrudTable/index.vue';
import BIconBox from '@/components/BIconBox.vue';

const { proxy } = getCurrentInstance();
const menusStore = useMenusStore();

const isWatchLoading = ref(false)
const columns = ref([
    {
        title: '显示名称',
        dataIndex: 'title',
        key: 'title',
        width: 150
    },
    {
        title: '菜单名称',
        dataIndex: 'name',
        key: 'name'
    },
    {
        title: '(路由)URL',
        dataIndex: 'path',
        key: 'path',
    },
    {
        title: '组件',
        dataIndex: 'component',
        key: 'component'
    },
    {
        title: '菜单类型',
        dataIndex: 'type',
        key: 'type'
    },
    {
        title: '是否重定向',
        dataIndex: 'redirect',
        key: 'redirect'
    },
    {
        title: '图标',
        dataIndex: 'icon',
        key: 'icon'
    },
    {
        title: '隐藏面包屑',
        dataIndex: 'hidden_breadcrumb',
        key: 'hidden_breadcrumb'
    },
    {
        title: '隐藏菜单',
        dataIndex: 'hidden',
        key: 'hidden'
    },
    {
        title: '是否固定',
        dataIndex: 'affix',
        key: 'affix'
    },
    // {
    //     title: '是否全屏',
    //     dataIndex: 'fullpage',
    //     key: 'fullpage'
    // },
    {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        fixed: 'right'
        // width: 100
    }
])

const onSwitchChange = async (data) => {
    try {
        isWatchLoading.value = true
        await proxy.$api.system.patchMenuDetailAPI(data)
        isWatchLoading.value = false
        // 重新获取菜单数据
        await reloadMenu()
        proxy.$message.success('修改成功')
    } catch (error) {
        isWatchLoading.value = false
        proxy.$message.error('修改失败')
    }
}

// 刷新菜单
const reloadMenu = async () => {
    // const res = await proxy.$api.system.getMenuAPI()
    // menusStore.setMenus(res.data.value)
    await tableRef.value.getData()
}

const tableRef = ref(null)
const modalFormData = reactive({
    id: '',
    title: '',
    name: '',
    path: '',
    component: '',
    redirect: '',
    parent: null
})

const rulesRef = ref({
    title: [
        { required: true, message: '请输入显示名称', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' }
    ],
    path: [
        { required: true, message: '请输入(路由)URL', trigger: 'blur' }
    ],
    component: [
        { required: false, message: '请输入组件路径', trigger: 'blur' }
    ],
    redirect: [
        { required: false, message: '请输入重定向地址', trigger: 'blur' }
    ],
    parent: [
        { required: false, message: '请选择上级菜单', trigger: 'blur' }
    ]
})

const showModal = (type, data) => {
    if (type === 'edit') {
        modalFormData.id = data.id
        modalFormData.title = data.meta.title
        modalFormData.name = data.name
        modalFormData.path = data.path
        modalFormData.component = data.component
        modalFormData.redirect = data.redirect
        modalFormData.parent = data.parent
    } else if (type === 'add') {
        for (const key in modalFormData) {
            if (key !== 'parent'){
                modalFormData[key] = ''
            }
        }
    }
}

// 图标选择器
const onIconChange = async (record) => {
    await onSwitchChange(record)
    await reloadMenu()
}

// 父级选择器
const treeData = computed(() => {
    return mapTreeData(menusStore.menuList)
})
// 映射数据结构
const mapTreeData = (data) => {
    return data.map(item => {
        return {
            value: item.id,
            label: item.meta.title,
            children: item.children ? mapTreeData(item.children) : []
        }
    })
}

// 提交表单
const submitEvent = async (type, data) => {
    let formData = {
        path: data.path,
        name: data.name,
        component: data.component,
        redirect: data.redirect,
        parent: data.parent,
        meta: {
            title: data.title,
        }
    }
    if (type === 'add') {
        const res = await proxy.$api.system.createMenuAPI(formData)
        await reloadMenu()
        proxy.$message.success('添加成功')
    } else if (type === 'edit') {
        formData.id = data.id
        await proxy.$api.system.patchMenuDetailAPI(formData)
    }
}

</script>